package com.itkjb.leisurely.resource.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itkjb.leisurely.core.base.service.impl.BaseServiceImpl;
import com.itkjb.leisurely.resource.sys.mapper.SysUserDepMapper;
import com.itkjb.leisurely.resource.sys.model.SysUserDepModel;
import com.itkjb.leisurely.resource.sys.model.SysUserRoleModel;
import com.itkjb.leisurely.resource.sys.model.dto.SysUserDepDTO;
import com.itkjb.leisurely.resource.sys.model.vo.SysUserVO;
import com.itkjb.leisurely.resource.sys.service.ISysUserDepService;
import com.itkjb.leisurely.resource.sys.service.ISysUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户组织关系对象，组织成员 服务实现类
 * </p>
 *
 * @author itkjb.com
 * @since 2020-07-17
 */
@Service
public class SysUserDepServiceImpl extends BaseServiceImpl<SysUserDepMapper, SysUserDepModel> implements ISysUserDepService {

    @Autowired
    ISysUserRoleService userRoleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysUserDepModel entity) {
        updateUserDepRole(entity);
        return super.save(entity);
    }

    private void updateUserDepRole(SysUserDepModel entity) {
        // 删除原有 改组织下的角色
        QueryWrapper<SysUserRoleModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRoleModel::getUserId, entity.getUserId())
                .eq(SysUserRoleModel::getDepId, entity.getDepId());
        userRoleService.remove(queryWrapper);
        // 重置在该组织下的角色
        if(entity.getRoleIds() !=null && entity.getRoleIds().size()>0){
            List<SysUserRoleModel> userRoleModels = new ArrayList<>(entity.getRoleIds().size());
            for (String  roleId : entity.getRoleIds()) {
                SysUserRoleModel userRoleModel = new SysUserRoleModel();
                userRoleModel.setUserId(entity.getUserId());
                userRoleModel.setRoleId(roleId);
                userRoleModel.setDepId(entity.getDepId());
                userRoleModels.add(userRoleModel);
            }
            userRoleService.saveBatch(userRoleModels);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SysUserDepModel entity) {
        updateUserDepRole(entity);
        return super.updateById(entity);
    }

    @Override
    public IPage<SysUserVO> getNonMembers(IPage<?> page, SysUserDepDTO user) {
        return this.baseMapper.getNonMembers(page,user);
    }

    @Override
    public IPage<SysUserDepModel> getDepMembers(IPage<?> page, SysUserDepDTO user) {
        return this.baseMapper.getDepMembers(page,user);
    }
    /**
     * 获取用户在指定组织下的数据权限
     * @param userId 用户id
     * @param depId 组织id
     * @return
     */
    @Override
    public int getUserCurrentDepDataLevel(String userId, String depId) {
        int dataLevel = 0;
        SysUserDepModel userDepModel = new SysUserDepModel();
        userDepModel.setUserId(userId);
        userDepModel.setDepId(depId);
        userDepModel.setStatus(1);
        userDepModel.setIsDel(false);
        List<SysUserDepModel> list = this.list(userDepModel);
        if(list !=null && list.size()>0){
            dataLevel = list.get(0).getDataLevel()==null?0:list.get(0).getDataLevel();
        }
        return dataLevel;
    }

    @Override
    public List<SysUserDepModel> getUserDepsInfo(String userId) {
        return this.baseMapper.getUserDepsInfo(userId);
    }

    /**
     * wrapper 组装器，构造条件查询
     * @author itkjb.com
     * @date  2020-07-17
     * @param wrapper
     * @param model 条件
     **/
    @Override
    protected void assembleWrapper(QueryWrapper<SysUserDepModel> wrapper, SysUserDepModel model) {
        // （代码生成器生成）自动生成了，list查询的时候，条件组装，开发者自行删除不需要的条件
        // 用户id
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getUserId()), SysUserDepModel::getUserId, model.getUserId() );
        // 组织id
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getDepId()), SysUserDepModel::getDepId, model.getDepId() );
        // 岗位id
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getStationId()), SysUserDepModel::getStationId, model.getStationId() );
        // 岗位名称
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getStationName()), SysUserDepModel::getStationName, model.getStationName() );
        // 用户岗位职级
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getUserPosition()), SysUserDepModel::getUserPosition, model.getUserPosition() );
        // 岗位职级编号，例如1，2，3
        wrapper.lambda().eq(model.getPositionCode() != null, SysUserDepModel::getPositionCode, model.getPositionCode() );
        // 用户员工编号
        wrapper.lambda().eq(StringUtils.isNotBlank(model.getUserEmployeeNum()), SysUserDepModel::getUserEmployeeNum, model.getUserEmployeeNum() );
        // 联系地址
        // wrapper.lambda().eq(StringUtils.isNotBlank(model.getLinkAddress()), SysUserDepModel::getLinkAddress, model.getLinkAddress() );
        // 数据权限 1 查看个人数据  2 查看本部门数据 4.当前组织以及下级数据 8:查看指定部门数据
        wrapper.lambda().eq(model.getDataLevel() != null, SysUserDepModel::getDataLevel, model.getDataLevel() );
        // 0：申请加入，待审核；1：正常；2：审核不通过，待完善信息；   -1 ：离职，删除
        wrapper.lambda().eq(model.getStatus() != null, SysUserDepModel::getStatus, model.getStatus() );
    }

    /**
     * wrapper 组装器，组装list查询时，查询的列
     * @author itkjb.com
     * @date  2020-07-17
     * @param wrapper
     * @param model
     * @return void
     * @since 2020-07-17
     **/
    @Override
    protected void buildListSelectColumns(QueryWrapper<SysUserDepModel> wrapper, SysUserDepModel model){
        buildCommonSelectColumns(wrapper, model);
    }

    /**
     * 组装列表查询的列（字段）
     * @date  2020-07-17
     * @param wrapper
     * @param model
     */
    protected void buildCommonSelectColumns(QueryWrapper<SysUserDepModel> wrapper, SysUserDepModel model){
        // 代码生成器生成，为了简化开发时，查询list时，查询指定字段，没必要查询所有参数
        wrapper.lambda().select(
            // id
            SysUserDepModel::getId,
            // 用户id
            SysUserDepModel::getUserId,
            // 组织id
            SysUserDepModel::getDepId,
            // 岗位id
            SysUserDepModel::getStationId,
            // 岗位名称
            SysUserDepModel::getStationName,
            // 用户岗位职级
            SysUserDepModel::getUserPosition,
            // 岗位职级编号，例如1，2，3
            SysUserDepModel::getPositionCode,
            // 用户员工编号
            SysUserDepModel::getUserEmployeeNum,
            // 联系地址
            SysUserDepModel::getLinkAddress,
            // 数据权限 1 查看个人数据  2 查看本部门数据 4.当前组织以及下级数据 8:查看指定部门数据
            SysUserDepModel::getDataLevel,
            // 0：申请加入，待审核；1：正常；2：审核不通过，待完善信息；   -1 ：离职，删除
            SysUserDepModel::getStatus,
            SysUserDepModel::getCreateTime
        );
    }


}
